﻿using RpcClient.Interface;
using RpcClient.Queue.Model;
using RpcClient.Rabbitmq;
using RpcClient.Rabbitmq.Interface;
using RpcClient.Rabbitmq.Model;
using RpcHelper;
using RpcModel;

namespace RpcClient.Collect
{
    /// <summary>
    /// 死信队列服务
    /// </summary>
    [Attr.ClassLifetimeAttr(Attr.ClassLifetimeType.单例)]
    internal class DeadQueueCollect : IDeadQueueCollect
    {
        private readonly IDeadSubscribe _Subscribe;
        private DeadMsg _MsgEvent;

        public bool IsInit { get; }
        public DeadQueueCollect()
        {
            RabbitmqConfig config = Config.WebConfig.GetRabbitmqConfig();
            if (config == null)
            {
                return;
            }
            RabbitmqQueue rabbitmq = new RabbitmqQueue(config);
            this._Subscribe = new DeadSubscribe(rabbitmq, RpcStateCollect.LocalSource, this._Callback);
            this.IsInit = true;
        }

        private void _Callback(DeadQueueMsg msg, string routeKey, BroadcastType type)
        {
            this._MsgEvent(msg, routeKey, type);
        }

        public void BindQueue(string queue, DeadMsg callback)
        {
            if (this._Subscribe == null)
            {
                throw new ErrorException("rpc.rabbitmq.no.config");
            }
            this._Subscribe.BindQueue(queue);
            this._MsgEvent += callback;
        }

    }
}
